import { useAPIUtils } from "@/components/APIUtilsProvider";
import PageLayout from "@/components/PageLayout";
import {
  ActionIcon,
  Avatar,
  Badge,
  Button,
  Center,
  Flex,
  Pagination,
  Paper,
  Table,
  TextInput,
  Tooltip,
} from "@mantine/core";
import { IconPlus, IconReload } from "@tabler/icons-react";
import { useState } from "react";
import { useImmer } from "use-immer";
import { ProductEdit } from "./ProductEditModal";

export default function ProductList() {
  const [pagingCondition, setPagingCondition] = useImmer({
    keyword: "",
    pageIndex: 0,
    pageSize: 10,
  });

  const [editing, setEditing] = useState(false);

  const { restGET, tanstackQuery, tanstackInvalidate, restPOST, restDELETE } =
    useAPIUtils();

  const productQuery = tanstackQuery("/api/admin/products", {});

  const reload = () => {
    tanstackInvalidate("/api/admin/products");
  };

  const perPage = pagingCondition.pageSize;
  const filteredItems = productQuery.data?.filter((product) =>
    product.name.includes(pagingCondition.keyword)
  );
  const totalPages = Math.ceil(filteredItems?.length / perPage);
  const rows = filteredItems
    ?.slice(
      pagingCondition.pageIndex * perPage,
      (pagingCondition.pageIndex + 1) * perPage
    )
    ?.map((product, index) => (
      <Table.Tr key={index}>
        <Table.Td>{filteredItems.indexOf(product) + 1}</Table.Td>

        <Table.Td>
          <Avatar
            src={product.meta.imageUrl}
            alt={product.name}
            size={"md"}
            radius={"sm"}
          />
        </Table.Td>
        <Table.Td>{product.name}</Table.Td>
        <Table.Td>{product.stock}</Table.Td>
        <Table.Td>
          <Badge color={product.onMarket ? "green.5" : "gray.5"} size="lg">
            {product.onMarket ? "在售" : "已下架"}
          </Badge>
        </Table.Td>
        <Table.Td>{product.meta.weight}</Table.Td>
        <Table.Td>
          <Button.Group>
            <Button
              variant="subtle"
              size="xs"
              onClick={() => window.open(`/products/${product.id}`, "_blank")}
            >
              详情
            </Button>
          </Button.Group>
        </Table.Td>
      </Table.Tr>
    ));

  return (
    <PageLayout title={"商品列表"}>
      <ProductEdit opened={editing} setOpened={setEditing} />
      <Flex
        mih={50}
        mb={20}
        gap="sm"
        justify="flex-end"
        align="center"
        direction="row"
        wrap="wrap"
      >
        <Tooltip label="新建" withArrow>
          <ActionIcon
            variant="subtle"
            radius="xl"
            aria-label="Settings"
            onClick={() => setEditing(true)}
          >
            <IconPlus style={{ width: "70%", height: "70%" }} stroke={1.5} />
          </ActionIcon>
        </Tooltip>
        <Tooltip label="刷新数据" withArrow>
          <ActionIcon
            variant="subtle"
            radius="xl"
            aria-label="Settings"
            onClick={reload}
          >
            <IconReload style={{ width: "70%", height: "70%" }} stroke={1.5} />
          </ActionIcon>
        </Tooltip>
        <TextInput
          w={"260px"}
          placeholder="请输入关键字"
          value={pagingCondition.keyword}
          onChange={(e) =>
            setPagingCondition({
              ...pagingCondition,
              pageIndex: 0,
              keyword: e.target.value,
            })
          }
        />
      </Flex>
      <Paper p={"md"}>
        <Table verticalSpacing={"sm"} highlightOnHover>
          <Table.Thead>
            <Table.Tr>
              <Table.Th w={"5%"}>序号</Table.Th>
              <Table.Th w={"5%"}>缩略图</Table.Th>
              <Table.Th w={"50%"}>商品名</Table.Th>
              <Table.Th w={"10%"}>库存</Table.Th>
              <Table.Th w={"10%"}>状态</Table.Th>
              <Table.Th w={"10%"}>权重</Table.Th>
              <Table.Th>操作</Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>{rows}</Table.Tbody>
        </Table>
      </Paper>
      <Center mt={40}>
        <Pagination
          total={totalPages}
          value={pagingCondition.pageIndex + 1}
          onChange={(e) => {
            setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
          }}
        />
      </Center>
    </PageLayout>
  );
}
